﻿using System.Data;
using System.Web;
using System.IO;
using OfficeOpenXml;
using OfficeOpenXml.Style;
using System;
using System.Collections.Generic;
using System.Net.Http;

namespace Library.Helpers
{
    public class ExcelExportHelper
    {
        public static HttpResponseMessage GenerateExcelResponseMessage<T>(List<T> list)
        {
            DataTable table = ListHelper.ToDataTable<T>(list);
            return GenerateExcelResponseMessage(table);
        }

        public static HttpResponseMessage GenerateExcelResponseMessage(DataTable data)
        {
            string fileName = "list_" + DateTime.Now.Minute + DateTime.Now.Second + ".xlsx";
            string fileType = "xlsx";
            byte[] content = ExcelExportHelper.GetExcelAsByteArray(data);
            Stream fileStream = StreamHelper.CreateStreamFromByteArray(content);
            return HttpResponseMessageHelper.CreateResponseMessage(fileStream, fileName, fileType);
        }

        public static byte[] GetExcelAsByteArray(DataTable tbl)
        {
            ExcelPackage pck = new OfficeOpenXml.ExcelPackage();
            ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Report 0");

            if (tbl.Rows.Count > 0)
                ws.Cells["A2"].LoadFromDataTable(tbl, false);

            //Header Titles
            string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            int i = 0;
            foreach (DataColumn column in tbl.Columns)
            {
                ws.Cells[alphabet[i].ToString() + "1"].Value = column.ColumnName;
                ws.Cells[alphabet[i].ToString() + "1"].Style.Font.Bold = true;                
                i++;
            }
            ws.Cells["A1"].AutoFitColumns();            

            return pck.GetAsByteArray();
        }
    }
}